22. 解决方案:列表推导式(选学)
练习解决方案:提取名字
names = ["Rick Sanchez", "Morty Smith", "Summer Smith", "Jerry Smith", "Beth Smith"]
first_names = [name.split()[0].lower() for name in names]
print(first_names)
输出:
['rick', 'morty', 'summer', 'jerry', 'beth']
练习解决方案:3 的倍数
multiples_3 = [x * 3 for x in range(1, 21)]
print(multiples_3)
输出:
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60]
练习解决方案:按得分过滤姓名
scores = {
"Rick Sanchez": 70,
"Morty Smith": 35,
"Summer Smith": 82,
"Jerry Smith": 23,
"Beth Smith": 98
}
passed = [name for name, score in scores.items() if score >= 65]
print(passed)
输出:
该输出中的元素顺序可能有变化,因为字典是无序的。
['Beth Smith', 'Summer Smith', 'Rick Sanchez']